// Copyright (c) 2023 Presto Labs Pte. Ltd.
// Author: tianqiang

#pragma once

#include <memory>
#include <string>

#include "coin2/base/string_util.h"
#include "coin2/exchange/base/symbology/spot_product.h"
#include "coin2/exchange/mexc/symbology_v3/currency.h"

namespace coin2::exchange::mexc::symbology_v3 {

class MexcProduct : public base::symbology::SpotProduct<MexcCurrency, MexcProduct>,
                    public base::symbology::ProductFromStrMixin<MexcProduct> {
 public:
  using ExchangeType = base::market::ExchangeType;
  using MarketType = base::market::MarketType;

  MexcProduct(const MexcCurrency& base, const MexcCurrency& quote)
      : SpotProduct(
            base,
            quote,
            ToMexcNativeProduct(base, quote),
            ToMexcNativeProduct(base, quote),
            ExchangeType::Mexc) {}

 public:
  static std::unique_ptr<MexcProduct> FromNativeStrImpl(
      const std::string& native_product,
      int64_t resolve_timestamp) {
    std::unique_ptr<MexcCurrency> base_ptr;
    std::unique_ptr<MexcCurrency> quote_ptr;
    bool success = ParseMexcNativeProduct(native_product, resolve_timestamp, &base_ptr, &quote_ptr);

    if (success) {
      return std::make_unique<MexcProduct>(*base_ptr, *quote_ptr);
    } else {
      return {};
    }
  }

 private:
  static bool ParseMexcNativeProduct(
      const std::string& product_str,
      int64_t resolve_timestamp,
      std::unique_ptr<MexcCurrency>* base_ptr,
      std::unique_ptr<MexcCurrency>* quote_ptr) {
    static const std::string quotes[] = {
        "USDT",
        "USDC",
        "ETH",
        "BTC",
        "BUSD",
        "TRX",
        "ADA",
        "EOS",
        "TRYB",
        "USDP",
        "DOGE",
        "TUSD"
    };

    const std::string& product_str_upper = StringToUpperCopy(product_str);

    for (const std::string& quote_cand : quotes) {
      if (StringEndsWith(product_str_upper, quote_cand)) {
        size_t base_len = product_str_upper.size() - quote_cand.size();
        std::string base = product_str_upper.substr(0, base_len);
        *base_ptr = MexcCurrency::FromNativeStrNoThrow(base, resolve_timestamp);
        *quote_ptr = MexcCurrency::FromNativeStrNoThrow(quote_cand, resolve_timestamp);
        return true;
      }
    }
    return false;
  }

  static std::string ToMexcNativeProduct(const MexcCurrency& base, const MexcCurrency& quote) {
    std::stringstream ss;
    ss << base.native_currency(MarketType::Spot) << quote.native_currency(MarketType::Spot);
    return ss.str();
  }
};

}  // namespace coin2::exchange::mexc::symbology_v3
